package com.ts.api.module.match.plan.internal.distribute.strategy;

import com.gitee.apanlh.exp.ParamParserException;
import com.gitee.apanlh.util.base.BigDecimalUtils;
import com.gitee.apanlh.util.base.IteratorUtils;
import com.gitee.apanlh.util.dataformat.JsonUtils;
import com.gitee.apanlh.util.id.IdUtils;
import com.gitee.apanlh.util.valid.ValidParam;
import com.ts.api.common.constant.productflow.ProductApplyFlowStatusEnum;
import com.ts.api.module.api.convert.core.http.client.ApiHttpMessage;
import com.ts.api.module.api.convert.platform.entity.RespPlatformMultiPhoneMaskDataExchange;
import com.ts.api.module.api.convert.platform.entity.RespPlatformPhoneMaskDataExchange;
import com.ts.api.module.api.convert.platform.handler.ApiPlatformPhoneMaskConvertHandler;
import com.ts.api.module.api.service.ApiBizRequiredService;
import com.ts.api.module.match.plan.internal.distribute.model.PlanDistribute;
import com.ts.api.module.match.plan.internal.distribute.model.PlanDistributeField;
import com.ts.api.module.match.plan.internal.distribute.model.PlanDistributePhoneMaskField;
import com.ts.api.module.match.plan.internal.distribute.model.PlanDistributePost;
import com.ts.api.module.match.plan.internal.distribute.model.PlanDistributeResult;
import com.ts.api.module.match.plan.model.AbstractPlanMatch;
import com.ts.api.module.product.entity.po.ProductApplyFlowPO;
import com.ts.api.module.product.entity.po.ProductPlanPO;
import com.ts.api.module.product.service.ProductPlanTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;

/**
 *  API渠道-平台计划分发
 *
 *  @author Pan
 */
@Service
public class ApiPlatformPhoneMaskDistribute implements PlanDistributeStrategy<ApiPlatformPhoneMaskConvertHandler> {

    @Autowired
    private BaseDistribute baseDistribute;
    @Autowired
    private ApiBizRequiredService apiBizRequiredService;
    @Autowired
    private ProductPlanTypeService productPlanTypeService;

    @Override
    public PlanDistributeResult preValidate(PlanDistribute planDistribute) {
        return baseDistribute.preValidate(planDistribute);
    }

    @Override
    public PlanDistributeResult distribute(PlanDistribute planDistribute) {
        return baseDistribute.distribute(planDistribute);
    }

    @Override
    public PlanDistributeField parseResponse(PlanDistribute planDistribute, ApiHttpMessage apiHttpMessage, ApiPlatformPhoneMaskConvertHandler handler) throws Exception {
        String reqId = planDistribute.getReqId();
        ProductPlanPO productPlanPO = planDistribute.getProductPlanPO();
        ProductApplyFlowPO currentDistributeFlow = planDistribute.getCurrentDistributeFlow();
        String responseBody = apiHttpMessage.getResponseBody();

        //  验证非空情况
        if (ValidParam.isEmpty(responseBody)) {
            throw new ParamParserException("解析失败-响应体返回空");
        }

        //  解析响应体
        RespPlatformMultiPhoneMaskDataExchange resp = handler.respDataExchange(responseBody);
        if (ValidParam.isNull(resp)) {
            throw new ParamParserException("撞库参数异常:API平台-掩码模式-未返回业务实体请检查");
        }

        //  验证返回业务消息是否成功
        if (!resp.getHasBizSuc()) {
            return PlanDistributeField.ofFail("API平台-掩码模式-处理响应结果-对方返回结果[失败]", ProductApplyFlowStatusEnum.PLAT_FORM_DATA_EXCHANGE_FAIL);
        }

        //  验证参数
        boolean hasPlatShare = productPlanTypeService.hasPlatShare(productPlanPO);
        boolean hasPlatOtherProvider = productPlanTypeService.hasPlatOtherProvider(productPlanPO);
        String errorMsg = baseDistribute.validRespPlatformByPhoneMask(resp, hasPlatShare, hasPlatOtherProvider);
        if (ValidParam.isNotEmpty(errorMsg)) {
            throw new ParamParserException("撞库参数异常:API平台-掩码模式-解析参数失败:" + errorMsg);
        }

        List<RespPlatformPhoneMaskDataExchange> listPhoneMask = resp.getListPhoneMask();
        if (ValidParam.isEmpty(listPhoneMask)) {
            throw new ParamParserException("API平台-掩码模式-对接代码-返回集合md5为null");
        }

        //  填充属性
        boolean hasPlatWeProvider = productPlanTypeService.hasPlatWeProvider(productPlanPO);
        IteratorUtils.array(listPhoneMask, t -> {
            //  如果为空则设置我方平台中的logo地址
            if (ValidParam.isEmpty(t.getLogoPath())) {
                t.setLogoPath(productPlanPO.getLogoPath());
            }
            //  如果我方接入对方文档没有applyId则设置applyId
            if (hasPlatWeProvider && ValidParam.isEmpty(t.getApplyId())) {
                t.setApplyId(IdUtils.getSimpleUuid());
            }
        });

        //  撞库流程http响应保存->序列化解析对象
        currentDistributeFlow.setRespData(JsonUtils.toJson(resp));

        return PlanDistributeField.ofPlatformPhoneMask(resp, reqId);
    }

    @Override
    public PlanDistributeResult post(PlanDistributePost planDistributePost) {
        //  获取字段对象
        PlanDistributeField planDistributeField = planDistributePost.getPlanDistributeField();
        List<PlanDistributePhoneMaskField> listPhoneMaskField = planDistributeField.getListPhoneMaskField();

        //  获取分发对象
        PlanDistribute planDistribute = planDistributePost.getPlanDistribute();
        ProductPlanPO productPlanPO = planDistribute.getProductPlanPO();

        //  获取价格
        AbstractPlanMatch abstractPlanMatch = planDistributePost.getAbstractPlanMatch();
        BigDecimal channelPrice = abstractPlanMatch.getChannelPrice();

        //  是否平台计划为分润模式
        boolean hasPlatShare = productPlanTypeService.hasPlatShare(productPlanPO);

        //  二次验证平台计划回传价格是否低于当前渠道价-低于剔除
        IteratorUtils.collection(listPhoneMaskField, (phoneMaskField, iterator) -> {
            BigDecimal resultPrice = phoneMaskField.getPrice();

            //  分润模式
            BigDecimal finalPrice;
            if (hasPlatShare) {
                //  原价 * 渠道分成份额% = 分润后的单价
                BigDecimal percent = BigDecimalUtils.division(productPlanPO.getShare(), 100);
                finalPrice = BigDecimalUtils.multiply(resultPrice, percent).setScale(2, RoundingMode.DOWN);
            } else {
                finalPrice = productPlanPO.getPrice();
            }

            //  剔除低于渠道单价的条目
            if (!apiBizRequiredService.requiredPlanPrice(finalPrice, channelPrice)) {
                iterator.remove();
                return ;
            }

            //  设置价格
            phoneMaskField.setPrice(finalPrice);
        });

        //  二次单价验证剔除过后-无分发记录
        if (ValidParam.isEmpty(listPhoneMaskField)) {
            PlanDistributeResult planDistributeResult = PlanDistributeResult.ofFail(planDistributePost);
            planDistributeResult.setBizErrorMsg("二次验证[单价]-无分发记录");
            planDistributeResult.setBizErrorType(ProductApplyFlowStatusEnum.PLAT_FORM_DATA_EXCHANGE_FAIL);
            return planDistributeResult;
        }
        return PlanDistributeResult.ofSuc(planDistributePost);
    }
}
